package com.javaee.shortlink.admin.toolkit;

import java.security.SecureRandom;

public final class RandomStringUtil {
    // 字符集，包括大写字母、小写字母和数字
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    // 使用 SecureRandom 生成更安全的随机数
    private static final SecureRandom random = new SecureRandom();

    /**
     * 生成包含英文字母和数字的6位随机字符串
     *
     * @return 6位随机字符串
     */
    public static String generateRandomString() {
        StringBuilder sb = new StringBuilder(6);
        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return sb.toString();
    }

    /**
     * 生成指定长度的随机字符串
     *
     * @param length 随机字符串长度
     * @return 随机字符串
     */
    public static String generateRandomString(int length) {
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return sb.toString();
    }
}
